/* 
 * File:   Texture.cpp
 * Author: noe
 * 
 * Created on 8 octobre 2013, 18:33
 */

#include "Texture.h"

Texture::Texture(std::string source) {
	load(source.c_str());
}

Texture::Texture(const Texture& orig) {
}

Texture::~Texture() {
}

bool Texture::load(std::string source)
{
	SDL_Surface *imageSDL = IMG_Load(source.c_str());
	
	if(imageSDL == 0)
    {
        std::cout << "Erreur : " << SDL_GetError() << "\n";
        return false;
    }
	
	std::cout << "texture id : " << this->textureId << "\n";
	glGenTextures(1, &this->textureId);
	std::cout << "texture id : " << this->textureId << "\n";

	glBindTexture(GL_TEXTURE_2D, this->textureId);
	
	GLenum formatInterne(0);
	GLenum format(0);
	
	if(imageSDL->format->BytesPerPixel == 3) //JPG
	{
 
		formatInterne = GL_RGB;

		if(imageSDL->format->Rmask == 0xff)
			format = GL_RGB;
		else
			format = GL_BGR;
	}
 
 	else if(imageSDL->format->BytesPerPixel == 4) //PNG
	{    
		formatInterne = GL_RGBA;

		if(imageSDL->format->Rmask == 0xff)
			format = GL_RGBA;
		else
			format = GL_BGRA;
	}
	
	else
	{
		std::cout << "Erreur dans le format de l'image\n";
		SDL_FreeSurface(imageSDL);
		
		return false;
	}
	
	std::cout << "largeur de l'image : " << imageSDL->pixels << "\n";

	
	glTexImage2D(GL_TEXTURE_2D, 0, formatInterne, imageSDL->w, imageSDL->h, 0, format, GL_UNSIGNED_BYTE, imageSDL->pixels);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
	
	glBindTexture(GL_TEXTURE_2D, 0);
	
	SDL_FreeSurface(imageSDL);
    return true;

}

GLuint Texture::getId() const
{
	return this->textureId;
}
